package com.hmkj.admin.controller.order;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmkj.admin.controller.BaseController;
import com.hmkj.admin.controller.GenericController;
import com.hmkj.admin.utils.AdminSessionHelper;
import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.entity.dtgrid.DtGrid;
import com.hmkj.common.entity.export.CustomExportUtils;
import com.hmkj.common.entity.export.ExportUtils;
import com.hmkj.common.utils.BigDecimalUtils;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.common.utils.ValidateUtils;
import com.hmkj.core.api.etonepay.utils.DateUtil;
import com.hmkj.core.constant.RiskNID;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.order.OrderModel;
import com.hmkj.core.po.amount.AccountLog;
import com.hmkj.core.po.amount.Cash;
import com.hmkj.core.po.amount.Recharge;
import com.hmkj.core.po.commo.Commo;
import com.hmkj.core.po.operate.Agent;
import com.hmkj.core.po.order.Order;
import com.hmkj.core.po.system.Admin;
import com.hmkj.core.po.user.User;
import com.hmkj.core.service.amount.AccountLogService;
import com.hmkj.core.service.amount.AccountService;
import com.hmkj.core.service.amount.CashService;
import com.hmkj.core.service.amount.RechargeService;
import com.hmkj.core.service.commo.CommoService;
import com.hmkj.core.service.operate.AgentService;
import com.hmkj.core.service.order.OrderService;
import com.hmkj.core.service.risk.RiskParamService;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(BaseController.BASE_URI)
public class OrderJsonController extends GenericController {

    @Resource
    private OrderService orderService;
    @Resource
    private AccountService accountService;
    @Resource
    private AccountLogService accountLogService;
    @Resource
    private RechargeService rechargeService;
    @Resource
    private CashService cashService;
    @Resource
    private CommoService commoService;
    @Resource
    AgentService agentService;
    @Resource
    private RiskParamService riskParamService;


    /**
     * 策略列表json数据
     */
    @ResponseBody
    @RequestMapping(value = "order/json/list", method = RequestMethod.POST)
    @RequiresPermissions("sys:order:list")
    public DtGrid listJson(String dtGridPager) throws Exception {
        DtGrid dtgrid = dataAuthority(dtGridPager, null);
        dtgrid  =  orderService.getDtGridList(dtgrid, OrderModel.class);
        if( dtgrid.getExhibitDatas()!=null &&  dtgrid.getExhibitDatas().size()>0){
            List<Object> objects =  new ArrayList<>();
            for (Object obj : dtgrid.getExhibitDatas()) {
                LinkedHashMap map = (LinkedHashMap) obj;
                BigDecimal fee = new BigDecimal(map.get("fee").toString());//手数
                BigDecimal number = new BigDecimal(map.get("number").toString());//手数
                map.put("synthesisFee",fee.multiply(number));
                objects.add(map);
            }
            dtgrid.setExhibitDatas(objects);
        }
        return dtgrid;
    }

    /**
     * 接单
     */
    @ResponseBody
    @RequestMapping(value = "order/json/taking", method = RequestMethod.POST)
    @RequiresPermissions("sys:order:taking")
    public ResultEntity taking(Integer id) throws Exception {
        Admin admin = AdminSessionHelper.getCurrAdmin();
        //1.模拟订单状态等基础校验
        Order order = checkOrder(id,"taking");
        orderService.takingOrder(order,admin.getBussId());
        return ok();
    }

    /**
     * 流单
     */
    @ResponseBody
    @RequestMapping(value = "order/json/flow", method = RequestMethod.POST)
    @RequiresPermissions("sys:order:flow")
    public ResultEntity flow(Integer id) throws Exception {
        //1.模拟订单状态等基础校验
        Order order = checkOrder(id,"flow");
        //2.退还点买人履约保证金，退还点买人手续费，退还投资人止盈保证金，
        orderService.flowOrder(order);
        return ok();
    }

    /**
     * 撤单
     */
    @ResponseBody
    @RequestMapping(value = "order/json/cancel", method = RequestMethod.POST)
    @RequiresPermissions("sys:order:cancel")
    public ResultEntity cancel(Integer id) throws Exception {
        //1.模拟订单状态等基础校验
        Order order = checkOrder(id,"cancel");
        orderService.cancelOrder(id,order.getUserId(),Order.CANCLETYPE.T2);
        return ok();
    }

    /**
     * 平仓
     */
    @ResponseBody
    @RequestMapping(value = "order/json/cover", method = RequestMethod.POST)
    @RequiresPermissions("sys:order:cover")
    public ResultEntity cover(Integer id,Integer number,BigDecimal settlePrice) throws Exception {
        //1.模拟订单状态等基础校验
        if(null == number || number<=0){
            throw new BussinessException("请输入平仓数量");
        }else if(!ValidateUtils.isNumeric(number.toString())){
            throw new BussinessException("输入平仓数量有误");
        }
        if(null == settlePrice || BigDecimalUtils.isLessThanOrEquals(settlePrice,BigDecimal.ZERO)){
            throw new BussinessException("请输入平仓价格");
        }else if(!ValidateUtils.isMoney(settlePrice.toString())){
            throw new BussinessException("输入平仓价格有误");
        }
        Order order = checkOrder(id,"cover");
        orderService.coverOrderHandler(order,number,settlePrice,Order.SETTLETYPE.T5);
        return ok();
    }

    /**
     * 交易汇总
     */
    @ResponseBody
    @RequestMapping(value = "order/json/form", method = RequestMethod.POST)
    @RequiresPermissions("sys:order:form")
    public ResultEntity formListJson(@RequestParam(value = "startTimeStr") String startTimeStr,
                                      @RequestParam(value = "endTimeStr") String endTimeStr,Integer agentId) throws Exception {
        Admin admin = AdminSessionHelper.getCurrAdmin();
        if(admin.getType() == Admin.TYPE.T3.code){
            agentId = admin.getBussId();
        }
        ResultEntity resultEntity = new ResultEntity();
        resultEntity.setData(orderService.userSum(startTimeStr,endTimeStr,agentId));
        resultEntity.setCode(ResultEntity.SUCCESS);
        return resultEntity;
    }

    /**
     * 其他汇总
     */
    @ResponseBody
    @RequestMapping(value = "order/json/other", method = RequestMethod.POST)
    public ResultEntity otherListJson(@RequestParam(value = "startTimeStr") String startTimeStr,
                                      @RequestParam(value = "endTimeStr") String endTimeStr,Integer agentId) throws Exception {
        ResultEntity resultEntity = new ResultEntity();
        Admin admin = AdminSessionHelper.getCurrAdmin();
        if(admin.getType() == Admin.TYPE.T3.code){
            agentId = admin.getBussId();
        }
        Map<String, Object> map = new HashMap<>();
        map = getOtherData(map,agentId,startTimeStr,endTimeStr);
        resultEntity.setData(map);
        resultEntity.setCode(ResultEntity.SUCCESS);
        return resultEntity;
    }

    /**
     * 策略持仓中json数据
     */
    @ResponseBody
    @RequestMapping(value = "order/json/position", method = RequestMethod.POST)
    @RequiresPermissions("sys:order:position")
    public DtGrid positionJson(String dtGridPager) throws Exception {
        DtGrid dtgrid = dataAuthority(dtGridPager, null);
        dtgrid =  orderService.getDtGridList(dtgrid, OrderModel.class);
        List<Commo> commos = commoService.select(new Commo(c->{
            c.setDelFlag(Commo.DELFLAG.NORMAL.code);
        }));
        if(!CollectionUtil.isNotEmpty(commos)){
            throw new BussinessException("品种查询有误");
        }
        Map<Integer,BigDecimal> exMap = new HashMap<>();
        Map<Integer,BigDecimal> poMap = new HashMap<>();
        Map<Integer,BigDecimal> waMap = new HashMap<>();
        Map<Integer,BigDecimal> npMap = new HashMap<>();
        for (Commo commo: commos){
            BigDecimal exchangeRate = riskParamService.getParamValue(RiskNID.EXCHANGE_RATE, commo.getId(), BigDecimal.class);//汇率
            BigDecimal pointVlaue = riskParamService.getParamValue(RiskNID.POINT_VALUE, commo.getId(), BigDecimal.class);//每点合约价格
            BigDecimal waveMin = riskParamService.getParamValue(RiskNID.WAVE_POINT_MIN, commo.getId(), BigDecimal.class); // 最小波动点数
            BigDecimal np = riskParamService.lastPrice(commo.getId());//最新价
            exMap.put(commo.getId(),exchangeRate);
            poMap.put(commo.getId(),pointVlaue);
            waMap.put(commo.getId(),waveMin);
            npMap.put(commo.getId(),np);
        }
        if( dtgrid.getExhibitDatas()!=null &&  dtgrid.getExhibitDatas().size()>0){
            List<Object> objects =  new ArrayList<>();
            for (Object obj : dtgrid.getExhibitDatas()) {
                LinkedHashMap map = (LinkedHashMap) obj;
                //计算浮动盈亏
                Integer direction = Integer.valueOf(map.get("direction").toString());
                BigDecimal openPrice = new BigDecimal(map.get("openPrice").toString());//开仓价
                BigDecimal number = new BigDecimal(map.get("number").toString());//手数
                Integer commoId = Integer.valueOf(map.get("commoId").toString());
                BigDecimal floatProfit;
                BigDecimal eRate = BigDecimal.ZERO;
                BigDecimal pVlaue = BigDecimal.ZERO;
                BigDecimal wMin = BigDecimal.ZERO;
                BigDecimal np = BigDecimal.ZERO;
                if(exMap.containsKey(commoId)){
                    eRate =  exMap.get(commoId);
                }
                if(poMap.containsKey(commoId)){
                    pVlaue = poMap.get(commoId);
                }
                if(waMap.containsKey(commoId)){
                    wMin = waMap.get(commoId);
                }
                if(npMap.containsKey(commoId)){
                    np = npMap.get(commoId);
                }
                if(direction.intValue()==Order.DIRECTION.T1.code){
                    floatProfit =  (np.subtract(openPrice)).multiply(pVlaue).divide(wMin).multiply(number).multiply(eRate);
                }else{
                    floatProfit =  (openPrice.subtract(np)).multiply(pVlaue).divide(wMin).multiply(number).multiply(eRate);
                }
                map.put("floatProfit",floatProfit);
                objects.add(map);
            }
            dtgrid.setExhibitDatas(objects);
        }
        return dtgrid;
    }

    /**
     * 策略委托中json数据
     */
    @ResponseBody
    @RequestMapping(value = "order/json/entrust", method = RequestMethod.POST)
    @RequiresPermissions("sys:order:entrust")
    public DtGrid entrustJson(String dtGridPager) throws Exception {
        DtGrid dtgrid = dataAuthority(dtGridPager, null);
        dtgrid =  orderService.getDtGridList(dtgrid, OrderModel.class);
        if( dtgrid.getExhibitDatas()!=null &&  dtgrid.getExhibitDatas().size()>0){
            List<Object> objects =  new ArrayList<>();
            for (Object obj : dtgrid.getExhibitDatas()) {
                LinkedHashMap map = (LinkedHashMap) obj;
                BigDecimal fee = new BigDecimal(map.get("fee").toString());//手数
                BigDecimal number = new BigDecimal(map.get("number").toString());//手数
                map.put("synthesisFee",fee.multiply(number));
                objects.add(map);
            }
            dtgrid.setExhibitDatas(objects);
        }
        return dtgrid;
    }

    /**
     * 策略委托中手动开仓
     */
    @ResponseBody
    @RequestMapping(value = "order/json/entrustDeal", method = RequestMethod.POST)
    @RequiresPermissions("sys:order:entrust:deal")
    public ResultEntity ebtrustHandDeal(Integer id,Integer openAmount,String openBusiNo,BigDecimal openPrice,String openTime) throws Exception {
        //基础校验
        Order order = checkOrder(id,"entrustDeal");
        if(null == openAmount || openAmount<= 0 || openAmount>order.getNumber()){
            throw new BussinessException("请正确填写开仓订单数量");
        }
        if(StringUtils.isBlank(openBusiNo)){
            throw new BussinessException("请填写开仓成交编号");
        }
        if(null == openPrice || openPrice.compareTo(BigDecimal.ZERO)<= 0){
            throw new BussinessException("请正确填写开仓价格");
        }
        if(StringUtils.isBlank(openTime)){
            throw new BussinessException("请填写开仓价格");
        }
        Date openDate = DateUtil.formateStringToDate(openTime,"yyyy-MM-dd HH:mm:ss");
        if(null == openDate){
            throw new BussinessException("开仓时间填写有误");
        }
        orderService.ebtrustHandDealOrder(order,openAmount,openBusiNo,openPrice,openDate);
        return ok();
    }

    /**
     * 策略结算中json数据
     */
    @ResponseBody
    @RequestMapping(value = "order/json/balance", method = RequestMethod.POST)
    @RequiresPermissions("sys:order:balance")
    public DtGrid balanceJson(String dtGridPager) throws Exception {
        DtGrid dtgrid = dataAuthority(dtGridPager, null);
        dtgrid =  orderService.getDtGridList(dtgrid, OrderModel.class);
        if( dtgrid.getExhibitDatas()!=null &&  dtgrid.getExhibitDatas().size()>0){
            List<Object> objects =  new ArrayList<>();
            for (Object obj : dtgrid.getExhibitDatas()) {
                LinkedHashMap map = (LinkedHashMap) obj;
                BigDecimal fee = new BigDecimal(map.get("fee").toString());//手数
                BigDecimal number = new BigDecimal(map.get("number").toString());//手数
                map.put("synthesisFee",fee.multiply(number));
                objects.add(map);
            }
            dtgrid.setExhibitDatas(objects);
        }
        return dtgrid;
    }

    /**
     * 策略结算中手动结算
     */
    @ResponseBody
    @RequestMapping(value = "order/json/balanceDeal", method = RequestMethod.POST)
    @RequiresPermissions("sys:order:balance:deal")
    public ResultEntity balanceHandDeal(Integer id,Integer settleAmount,String settleBusiNo,String settlePrice,String settleTime) throws Exception {
        //基础校验
        Order order = checkOrder(id,"balanceDeal");
        if(null == settleAmount || settleAmount<= 0 || settleAmount>order.getNumber()){
            throw new BussinessException("请正确填写平仓订单数量");
        }
        if(StringUtils.isBlank(settleBusiNo)){
            throw new BussinessException("请填写平仓成交编号");
        }
        if(StringUtils.isBlank(settlePrice) || !ValidateUtils.isPrice(settlePrice) || new BigDecimal(settlePrice).compareTo(BigDecimal.ZERO)<= 0){
            throw new BussinessException("请正确填写平仓价格");
        }
        if(StringUtils.isBlank(settleTime)){
            throw new BussinessException("请填写平仓时间");
        }
        Date settleDate = DateUtil.formateStringToDate(settleTime,"yyyy-MM-dd HH:mm:ss");
        if(null == settleDate){
            throw new BussinessException("开仓时间填写有误");
        }
        orderService.balanceHandDealOrder(order,settleAmount,settleBusiNo,new BigDecimal(settlePrice),settleDate);
        return ok();
    }

    /**
     * 订单操作基础校验
     *
     * @param id
     */
    Order checkOrder(Integer id, String option) {
        if (null == id) {
            throw new BussinessException("订单参数有误");
        }
        Order order = orderService.selectByPrimaryKey(id);
        if (null == order) {
            throw new BussinessException("订单不存在");
        }
        //获取当前登录用户检验是否为投资人
        Admin admin = AdminSessionHelper.getCurrAdmin();
        if(admin.getType().intValue() == Admin.TYPE.T2.code){
            if(order.getInvestId().intValue() != admin.getBussId().intValue()){ throw new BussinessException("您无权操作该订单"); }
        }
        if ("taking".equals(option)) {//接单
            if(admin.getType().intValue() != Admin.TYPE.T2.code){
                throw new BussinessException("请指定投资人接单");
            }
            if (order.getStatus() != Order.STATUS.T1.code) {
                throw new BussinessException("订单状态已更改，接单操作失败");
            }
        } else if ("flow".equals(option)) {
            if (order.getStatus() != Order.STATUS.T1.code) {
                throw new BussinessException("订单状态已更改，流单操作失败");
            }
        } else if ("cancel".equals(option)) {
            if (order.getStatus() != Order.STATUS.T2.code && order.getStatus() != Order.STATUS.T4.code) {
                throw new BussinessException("订单状态已更改，撤单操作失败");
            }
        } else if ("cover".equals(option)) {
            if (order.getStatus() != Order.STATUS.T3.code && order.getStatus() != Order.STATUS.T4.code) {
                throw new BussinessException("订单状态已更改，平仓操作失败");
            }
        }else if("entrustDeal".equals(option)){
            if (order.getStatus() != Order.STATUS.T2.code) {
                throw new BussinessException("订单状态已更改，接单操作失败");
            }
        }else if("balanceDeal".equals(option)){
            if (order.getStatus() != Order.STATUS.T4.code) {
                throw new BussinessException("订单状态已更改，接单操作失败");
            }
        }
        return order;
    }


    /**
     * 列表导出
     *
     * @param dtGridPager
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "order/json/export", method = RequestMethod.POST)
    public ResultEntity export(String dtGridPager, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 执行导出
        DtGrid dtgrid = dataAuthority(dtGridPager, null);
        dtgrid  =  orderService.getDtGridListExport(dtgrid, OrderModel.class);
        if( dtgrid.getExhibitDatas()!=null &&  dtgrid.getExhibitDatas().size()>0){
            List<Object> objects =  new ArrayList<>();
            for (Object obj : dtgrid.getExhibitDatas()) {
                LinkedHashMap map = (LinkedHashMap) obj;
                BigDecimal fee = new BigDecimal(map.get("fee").toString());//手续费
                BigDecimal number = new BigDecimal(map.get("number").toString());//手数
                map.put("synthesisFee",fee.multiply(number));
                objects.add(map);
            }
            ObjectMapper mapper = new ObjectMapper();
            String dataJsonStr = JSON.toJSONString(objects);
            List<Map<String, Object>> exportDatas = mapper.readValue(dataJsonStr, new TypeReference<List<HashMap<String, Object>>>() {
            });
            dtgrid.setExportDatas(exportDatas);
        }
        ExportUtils.export(request, response, dtgrid);
        return ok();
    }

    /**
     * 交易数据报表导出
     */
    @ResponseBody
    @RequestMapping(value = "orderFrom/json/export", method = RequestMethod.POST)
    public ResultEntity exportSources(String startTimeStr,String endTimeStr,Integer agentId,HttpServletRequest request, HttpServletResponse response) throws Exception {
        String agentName = "全部";
        if(null != agentId){
            Agent agent = agentService.selectByPrimaryKey(agentId);
            agentName = agent.getName();
        }
        // 执行导出
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = sdf.format(new Date());
        Integer agentid = null;
        if(agentId !=null && !agentId.equals("")){
           agentid = Integer.valueOf(agentId);
        }
        Map<String, Object> map = new HashMap<>();
        Admin admin = AdminSessionHelper.getCurrAdmin();
        if(admin.getType() == Admin.TYPE.T3.code){
            agentid = admin.getBussId();
        }
        List<OrderModel> orderModels = orderService.userSum(startTimeStr,endTimeStr,agentid);
        map = getTradeData(map,orderModels);
        map = getOtherData(map,agentid,startTimeStr,endTimeStr);
        CustomExportUtils.exportExcel(map,request,response,agentName+"-交易数据报表"+dateStr);
        return ok();
    }

    private Map<String, Object> getTradeData( Map<String, Object> map, List<OrderModel> orders){
        BigDecimal tUser  = BigDecimal.ZERO;
        BigDecimal tNumBuy  = BigDecimal.ZERO;
        BigDecimal tProBuy  = BigDecimal.ZERO;
        BigDecimal tNumFol  = BigDecimal.ZERO;
        BigDecimal tProFol  = BigDecimal.ZERO;
        BigDecimal tPen  = BigDecimal.ZERO;
        BigDecimal tFee  = BigDecimal.ZERO;
        BigDecimal tdiv  = BigDecimal.ZERO;
        for(OrderModel order: orders){
            if(order.getCode().equals("GC")){
                map.put("userGC",order.getSumUser());
                map.put("numBuyGC",order.getSumBuyNum());
                map.put("proBuyGC",order.getSumBuyProfit());
                map.put("numFolGC",order.getSumFollowNum());
                map.put("proFolGC",order.getSumFollowProfit());
                map.put("penGC",order.getSumPenetrate());
                map.put("feeGC",order.getSumFee());
                map.put("divGC",order.getSumDivided());
            }else if(order.getCode().equals("CL")){
                map.put("userCL",order.getSumUser());
                map.put("numBuyCL",order.getSumBuyNum());
                map.put("proBuyCL",order.getSumBuyProfit());
                map.put("numFolCL",order.getSumFollowNum());
                map.put("proFolCL",order.getSumFollowProfit());
                map.put("penCL",order.getSumPenetrate());
                map.put("feeCL",order.getSumFee());
                map.put("divCL",order.getSumDivided());
            }else if(order.getCode().equals("SI")){
                map.put("userSI",order.getSumUser());
                map.put("numBuySI",order.getSumBuyNum());
                map.put("proBuySI",order.getSumBuyProfit());
                map.put("numFolSI",order.getSumFollowNum());
                map.put("proFolSI",order.getSumFollowProfit());
                map.put("penSI",order.getSumPenetrate());
                map.put("feeSI",order.getSumFee());
                map.put("divSI",order.getSumDivided());
            }else if(order.getCode().equals("HSI")){
                map.put("userHSI",order.getSumUser());
                map.put("numBuyHSI",order.getSumBuyNum());
                map.put("proBuyHSI",order.getSumBuyProfit());
                map.put("numFolHSI",order.getSumFollowNum());
                map.put("proFolHSI",order.getSumFollowProfit());
                map.put("penHSI",order.getSumPenetrate());
                map.put("feeHSI",order.getSumFee());
                map.put("divHSI",order.getSumDivided());
            }else if(order.getCode().equals("MHI")){
                map.put("userMHI",order.getSumUser());
                map.put("numBuyMHI",order.getSumBuyNum());
                map.put("proBuyMHI",order.getSumBuyProfit());
                map.put("numFolMHI",order.getSumFollowNum());
                map.put("proFolMHI",order.getSumFollowProfit());
                map.put("penMHI",order.getSumPenetrate());
                map.put("feeMHI",order.getSumFee());
                map.put("divMHI",order.getSumDivided());
            }else if(order.getCode().equals("DAX")) {
                map.put("userDAX",order.getSumUser());
                map.put("numBuyDAX",order.getSumBuyNum());
                map.put("proBuyDAX",order.getSumBuyProfit());
                map.put("numFolDAX",order.getSumFollowNum());
                map.put("proFolDAX",order.getSumFollowProfit());
                map.put("penDAX",order.getSumPenetrate());
                map.put("feeDAX",order.getSumFee());
                map.put("divDAX",order.getSumDivided());
            }
            tUser = tUser.add(BigDecimal.valueOf(order.getSumUser()));
            tNumBuy = tNumBuy.add(BigDecimal.valueOf(order.getSumBuyNum()));
            tProBuy = tProBuy.add(order.getSumBuyProfit());
            tNumFol = tNumFol.add(BigDecimal.valueOf(order.getSumFollowNum()));
            tProFol = tProFol.add(order.getSumFollowProfit());
            tPen = tPen.add(order.getSumPenetrate());
            tFee = tFee.add(order.getSumFee());
            tdiv = tdiv.add(order.getSumDivided());
        }
        map.put("totalUser",tUser);
        map.put("totalNumBuy",tNumBuy);
        map.put("totalProBuy",tProBuy);
        map.put("totalNumFol",tNumFol);
        map.put("totalProFol",tProFol);
        map.put("totalPen",tPen);
        map.put("totalFee",tFee);
        map.put("totalDiv",tdiv);
        return  map;
    }

    private Map<String, Object> getOtherData( Map<String, Object> map,Integer agentid,String startTimeStr,String endTimeStr){
        //推广佣金支出
        BigDecimal defray = accountLogService.selectSumAmountByType(AccountLog.TYPE.T11,startTimeStr,endTimeStr,agentid);
        //积分抵扣 暂无
        //点买人可用余额
        BigDecimal availableBuy = accountService.selectSumAvailableByType(User.TYPE.T1.code,agentid,startTimeStr,endTimeStr);
        //点买人冻结余额
        BigDecimal freezeBuy = accountService.selectSumFreezeByType(User.TYPE.T1.code,agentid,startTimeStr,endTimeStr);
        //投资人可用余额
        BigDecimal availableInv = accountService.selectSumAvailableByType(User.TYPE.T2.code,agentid,startTimeStr,endTimeStr);
        //投资人冻结余额
        BigDecimal freezeInv = accountService.selectSumFreezeByType(User.TYPE.T2.code,agentid,startTimeStr,endTimeStr);
        //快捷充值金额
        BigDecimal quickAmo = rechargeService.selectSumAmountByType(1,agentid, startTimeStr,endTimeStr,Recharge.TYPE.T1.code);
        //支付宝充值金额
        BigDecimal baoAmo = rechargeService.selectSumAmountByType(1, agentid, startTimeStr,endTimeStr,Recharge.TYPE.T2.code);
        //其它充值金额
        BigDecimal otherAmo = rechargeService.selectSumAmountByType(2,agentid, startTimeStr,endTimeStr, Recharge.TYPE.T1.code, Recharge.TYPE.T2.code);
        //用户提现金额
        BigDecimal cashAmo = cashService.selectSumAmountByStatus(Cash.STATUS.T4.code,startTimeStr,endTimeStr,agentid);
        //用户提现笔数
        long cashNum = cashService.countByStatus(Cash.STATUS.T4.code,startTimeStr,endTimeStr,agentid);
        if (defray == null) {
            map.put("defray", BigDecimal.ZERO);
        } else {
            map.put("defray", defray);
        }
        if (availableBuy == null) {
            map.put("availableBuy", BigDecimal.ZERO);
        } else {
            map.put("availableBuy", availableBuy);
        }
        if (freezeBuy == null) {
            map.put("freezeBuy", BigDecimal.ZERO);
        } else {
            map.put("freezeBuy", freezeBuy);
        }
        if (availableInv == null) {
            map.put("availableInv", BigDecimal.ZERO);
        } else {
            map.put("availableInv", availableInv);
        }
        if (freezeInv == null) {
            map.put("freezeInv", BigDecimal.ZERO);
        } else {
            map.put("freezeInv", freezeInv);
        }
        if (quickAmo == null) {
            map.put("quickAmo", BigDecimal.ZERO);
        } else {
            map.put("quickAmo", quickAmo);
        }
        if (baoAmo == null) {
            map.put("baoAmo", BigDecimal.ZERO);
        } else {
            map.put("baoAmo", baoAmo);
        }
        if (otherAmo == null) {
            map.put("otherAmo", BigDecimal.ZERO);
        } else {
            map.put("otherAmo", otherAmo);
        }
        if (cashAmo == null) {
            map.put("cashAmo", BigDecimal.ZERO);
        } else {
            map.put("cashAmo", cashAmo);
        }
        map.put("cashNum", cashNum);
        return  map;
    }


}